/*
 * Copyright 2009 XueSong Guo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.webwheel.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 在客户端弹出通知对话框并在页面上重定向其他页面的动作结果。
 */
public class AlertRedirectResult extends JavascriptResult {

    private String message;
    private String url;
    private String win;

    /**
     * 构造方法
     * @param message 弹出消息
     * @param url 重定向地址
     */
    public AlertRedirectResult(String message, String url) {
        this(message, url, null);
    }

    /**
     * 构造方法
     * @param message 弹出消息
     * @param url 重定向地址
     * @param win 重定向的窗口名称，例如“_self”、“_top”等等
     */
    public AlertRedirectResult(String message, String url, String win) {
        super(null);
        this.message = message;
        this.url = url;
        this.win = win;

    }

    /**
     * 输出结果到客户端
     * @throws IOException 输入输出异常
     */
    public void render() throws IOException {
        HttpServletRequest request = context.getRequest();
        StringBuilder sb = new StringBuilder();
        if(message!=null) {
            message = message.replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r").replace("'", "\\'");
            sb.append("alert('" + message + "');");
        }
        if (url != null) {
            if (url.startsWith("/")) {
                String cp = request.getContextPath();
                if (!cp.isEmpty()) url = cp + url;
            }
            if (win == null) {
                sb.append("window.location.href='").append(url).append("';");
            } else {
                sb.append("window.open('" + url + "', '" + win + "');");
            }
        }
        scripts = sb.toString();
        super.render();
    }
}
